using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using Microsoft.ApplicationBlocks.Data;
using System.Data;
using System.Net;

namespace AutoRuParser
{
  static class Operations
  {
    public static void UnionRecords(string connString)
    {
      try
      {
        SqlHelper.ExecuteScalar(connString, CommandType.StoredProcedure, "sp_Union");
      }
      catch (SqlException e)
      {
        Console.WriteLine(string.Format("SQL Error: {0}", e.Message));
      }
    }

    private static void SetValues(int Id, int changes, string price, string mark, string model, string modification, string connString)
    {
        SqlParameter[] sqlParam = new SqlParameter[6];
        sqlParam[0] = new SqlParameter("@price", price);
        sqlParam[1] = new SqlParameter("@mark", String.IsNullOrEmpty(mark) ? String.Empty : mark);
        sqlParam[2] = new SqlParameter("@model", String.IsNullOrEmpty(model) ? String.Empty : model);
        sqlParam[3] = new SqlParameter("@modification", String.IsNullOrEmpty(modification) ? String.Empty : modification);
        sqlParam[4] = new SqlParameter("@id", Id);
        sqlParam[5] = new SqlParameter("@changes", changes);
        try
        {
            SqlHelper.ExecuteScalar(connString, "UpdatePrice", sqlParam);
        }
        catch (SqlException e)
        {
            Console.WriteLine(string.Format("SQL Error: {0}", e.Message));
        }
    }

    private static void SetStatus(int Id, string status, string connString)
    {
      string commText = "UPDATE [Auction].[dbo].[Merged]" +
                  "SET" +
                  "[creationdate] = @creationdate" +
                  ",[status] = @status" +
                  " WHERE id=@id"; 

      SqlParameter[] sqlParam = new SqlParameter[4];
      sqlParam[0] = new SqlParameter("@id", Id);
      sqlParam[1] = new SqlParameter("@status", status);
      sqlParam[2] = new SqlParameter("@creationdate", DateTime.Now);
      try
      {
        SqlHelper.ExecuteScalar(connString, CommandType.Text, commText, sqlParam);
      }
      catch (SqlException e)
      {
        Console.WriteLine(string.Format("SQL Error: {0}", e.Message));
      }
    }
    public static void ChangeRecordStatus(string connString)
    {
      int Id = 0;
      string strURL = string.Empty;
      string price = string.Empty;
      string mark = string.Empty;
      string model = string.Empty;
      string modification = string.Empty;
      HtmlParser htmlParser = new HtmlParser(null, null, 0);


      DataSet ds = SqlHelper.ExecuteDataset(connString, CommandType.StoredProcedure, "sp_GetAllId");
      int count = ds.Tables[0].Rows.Count;
      foreach (DataRow dr in ds.Tables[0].Rows)
      {
        Id = (Int32) dr["id"];
        strURL = dr["Url"].ToString();
        htmlParser.CurrentPath = strURL;
        int changes = 0;
        if (htmlParser.CurrentLinesOfPage != null)
        {
            Auto auto = htmlParser.ReadDataToAuto();
            price = htmlParser.RecoverPrice(dr["price"].ToString());
            price = String.IsNullOrEmpty(price) ? dr["price"].ToString() : price;
            changes = htmlParser.GetChanges(dr["price"].ToString(), price, GetRates(connString));
            mark = auto.mark;
            model = auto.model;
            modification = auto.modification;
            //mark = htmlParser.RecoverMark(dr["mark"].ToString(), ref model);
            //mark = String.IsNullOrEmpty(mark) ? dr["mark"].ToString() : mark;
            //model = htmlParser.RecoverModel(model);
            //modification = htmlParser.RecoverModification(dr["modification"].ToString(), model);
        }
        HttpWebRequest req = null;

        try
        {
          req = HttpWebRequest.Create(strURL) as HttpWebRequest;
          HttpWebResponse res = req.GetResponse() as HttpWebResponse;
          if (res.StatusCode == HttpStatusCode.OK)
          {
              SetValues(Id, changes, price, mark, model, modification, connString);
              Console.WriteLine(string.Format("Response Status Code ok; URL: {0}; Code: {1}; Remains {2} records",
              strURL, "OK", count.ToString()));
          }
        }
        catch (WebException ex)
        {
          Console.WriteLine(string.Format("Change status of record on 'Sold'; URL: {0}; Remains {2} records Exception: {1}", strURL, ex.Message, count.ToString()));
          SetStatus(Id, "Sold", connString);
        }
        finally
        {
          count--;
          req.Abort();
        }
      }
    }
    public static DataSet GetRates(string connString)
    {
        try
        {
            return SqlHelper.ExecuteDataset(connString, CommandType.StoredProcedure, "sp_GetRates");
        }
        catch (SqlException e)
        {
            Console.WriteLine(string.Format("SQL Error: {0}", e.Message));
        }
        return null;
    }

  }
}
